package edu.gdkm.ssm.controller;

import edu.gdkm.ssm.domain.Role;
import edu.gdkm.ssm.domain.UserInfo;
import edu.gdkm.ssm.service.IRoleService;
import edu.gdkm.ssm.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @GetMapping("findAll.do")
    public ModelAndView findAll() throws Exception{
        List<UserInfo> userInfos = userService.findAll();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("userList", userInfos);
        modelAndView.setViewName("user-list");
        return modelAndView;
    }

    @PostMapping("save.do")
    @PreAuthorize("authentication.principal.username=='Boss'") // 表示只有Boss用户名才能操作
    public String save(UserInfo userInfo) throws Exception{
        this.userService.save(userInfo);
        return "redirect:findAll.do";
    }

    @GetMapping("findById.do")
    @PreAuthorize("hasRole('ROLE_ADMIN')") // 判断是否有ROLE_ADMIN权限
    public ModelAndView findById(@RequestParam(name = "id", required = true) String id) throws Exception{
        UserInfo userInfo = this.userService.findById(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user", userInfo);
        modelAndView.setViewName("user-show");
        return modelAndView;
    }

    @GetMapping("findUserByIdAndAllRole.do")
    public ModelAndView findUserByIdAndAllRole(String id) throws Exception{
        UserInfo userInfo = this.userService.findById(id);
        List<Role> roles = this.roleService.findOtherRole(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user", userInfo);
        modelAndView.addObject("roleList", roles);
        modelAndView.setViewName("user-role-add");
        return modelAndView;
    }

    @PostMapping("addRoleToUser.do")
    public String addRoleToUser(@RequestParam(name = "userId", required = true) String userId,
                                @RequestParam(name = "ids", required = true) String[] roleIds) throws Exception{
        this.userService.addRoleToUser(userId, roleIds);
        return "redirect:findAll.do";
    }

}
